const api = require('../../utils/request.js');
const Cart = require('../../utils/cart.js');

Page({
  data: {
    productId: '',
    product: null,
    quantity: 1,
    loading: true
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        productId: options.id
      });
      this.loadProductDetail();
    }
  },

  async loadProductDetail() {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      const result = await api.getProductById(this.data.productId);
      
      if (result.code === 200 && result.data) {
        this.setData({
          product: result.data,
          loading: false
        });
      }
    } catch (error) {
      console.error('加载商品详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({
        loading: false
      });
    } finally {
      wx.hideLoading();
    }
  },

  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
    }
  },

  increaseQuantity() {
    this.setData({
      quantity: this.data.quantity + 1
    });
  },

  addToCart() {
    if (!this.data.product) {
      return;
    }

    const product = this.data.product;
    for (let i = 0; i < this.data.quantity; i++) {
      Cart.addToCart(product);
    }

    wx.showToast({
      title: `已加入购物车 x${this.data.quantity}`,
      icon: 'success',
      duration: 2000
    });
  },

  goToCart() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  }
});
